<template>
  <div class="win10-desktop" @contextmenu.prevent="showDesktopContextMenu">
    <!-- 动态壁纸背景 -->
    <DesktopWallpaper :wallpaper="currentWallpaper" />

    <!-- 桌面图标区域 -->
    <DesktopIcons
      :icons="desktopIcons"
      :selected-icons="selectedIcons"
      @select="selectIcon"
      @open="openIcon"
      @dragstart="startDrag"
      @contextmenu="showIconContextMenu"
    />

    <!-- 打开的窗口 -->
    <DesktopWindows
      :windows="openWindows"
      :active-window-id="activeWindow"
      @activate="activateWindow"
      @dragstart="startWindowDrag"
      @minimize="minimizeWindow"
      @toggle-maximize="toggleMaximize"
      @close="closeWindow"
      @resize-start="startResize"
    />

    <!-- 任务栏 -->
    <Taskbar
      :windows="openWindows"
      :active-window-id="activeWindow"
      :time="currentTime"
      :date="currentDate"
      @toggle-start-menu="toggleStartMenu"
      @activate-window="activateWindow"
      @show-notifications="showNotifications"
      @show-calendar="showCalendar"
    />

    <!-- 桌面右键菜单 -->
    <ContextMenu
      :show="contextMenu.show"
      :x="contextMenu.x"
      :y="contextMenu.y"
      :items="contextMenu.items"
      @hide="hideContextMenu"
    />

    <!-- 应用管理对话框 -->
    <AppManageDialog
      v-model="appManageDialog"
      :available-apps="availableApps"
      :desktop-icons="desktopIcons"
      @add-app="addAppToDesktop"
      @remove-app="removeAppFromDesktop"
      @open-app="openIcon"
      @clear-desktop="clearDesktop"
    />

    <!-- 壁纸选择对话框 -->
    <WallpaperDialog
      v-model="wallpaperDialog"
      :current-wallpaper="currentWallpaper"
      :static-wallpapers="staticWallpapers"
      :dynamic-wallpapers="dynamicWallpapers"
      @change="changeWallpaper"
    />

    <!-- 显示设置对话框 -->
    <DisplaySettingsDialog
      v-model="displaySettingsDialog"
      :settings="displaySettings"
      @change="updateDisplaySettings"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, markRaw } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Monitor, DataBoard, UserFilled, Document, HomeFilled, ShoppingCart, Box,
  Money, Refresh, Setting, Picture, FolderOpened, Files, MagicStick, 
  Cloudy, Star, Lightning, Basketball, Histogram, TrendCharts, Grid,
  Sunny, Service, Operation, PieChart, Platform, Menu,
  Goods, House, TakeawayBox, Stamp, Wallet, DocumentCopy, PriceTag,
  Notebook, OfficeBuilding, Suitcase, Tools, Tickets, Reading, Trophy,
  VideoCamera, ChatDotSquare, Management, DocumentChecked
} from '@element-plus/icons-vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 导入API
import { keyUser, valueUser } from '@/api/data'

// 导入组件
import DesktopWallpaper from './components/DesktopWallpaper.vue'
import DesktopIcons from './components/DesktopIcons.vue'
import DesktopWindows from './components/DesktopWindows.vue'
import Taskbar from './components/Taskbar.vue'
import ContextMenu from './components/ContextMenu.vue'
import AppManageDialog from './components/AppManageDialog.vue'
import WallpaperDialog from './components/WallpaperDialog.vue'
import DisplaySettingsDialog from './components/DisplaySettingsDialog.vue'

// 导入动态背景组件
import ParticleBackground from '@/views/system/backgrounds/ParticleBackground.vue'
import BubbleBackground from '@/views/system/backgrounds/BubbleBackground.vue'
import MatrixBackground from '@/views/system/backgrounds/MatrixBackground.vue'
import GeometryBackground from '@/views/system/backgrounds/GeometryBackground.vue'
import StarBackground from '@/views/system/backgrounds/StarBackground.vue'
import WaveBackground from '@/views/system/backgrounds/WaveBackground.vue'
import NeonBackground from '@/views/system/backgrounds/NeonBackground.vue'
import GradientBackground from '@/views/system/backgrounds/GradientBackground.vue'
import SnowBackground from '@/views/system/backgrounds/SnowBackground.vue'
import FireworksBackground from '@/views/system/backgrounds/FireworksBackground.vue'
import AbstractBackground from '@/views/system/backgrounds/AbstractBackground.vue'
import ScanBackground from '@/views/system/backgrounds/ScanBackground.vue'
import RainbowFlowBackground from '@/views/system/backgrounds/RainbowFlowBackground.vue'
import AuroraBackground from '@/views/system/backgrounds/AuroraBackground.vue'
import LightRippleBackground from '@/views/system/backgrounds/LightRippleBackground.vue'
import TimeTunnelBackground from '@/views/system/backgrounds/TimeTunnelBackground.vue'
import DigitalRainBackground from '@/views/system/backgrounds/DigitalRainBackground.vue'
import CosmicBackground from '@/views/system/backgrounds/CosmicBackground.vue'
import PlasmaBackground from '@/views/system/backgrounds/PlasmaBackground.vue'
import SakuraBackground from '@/views/system/backgrounds/SakuraBackground.vue'
import MeteorShowerBackground from '@/views/system/backgrounds/MeteorShowerBackground.vue'
import ButterflyBackground from '@/views/system/backgrounds/ButterflyBackground.vue'
import DNAHelixBackground from '@/views/system/backgrounds/DNAHelixBackground.vue'
import CircuitBoardBackground from '@/views/system/backgrounds/CircuitBoardBackground.vue'
import HeartBeatBackground from '@/views/system/backgrounds/HeartBeatBackground.vue'

const router = useRouter()

// ==================== 时间相关 ====================
const currentTime = ref('')
const currentDate = ref('')

const updateDateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

// ==================== 壁纸管理 ====================
const wallpaperDialog = ref(false)

// ==================== 显示设置 ====================
const displaySettingsDialog = ref(false)
const displaySettings = ref({
  iconSize: 56,
  iconSpacing: 110,
  showIconLabel: true,
  taskbarPosition: 'bottom',
  autoHideTaskbar: false,
  smallTaskbarIcons: false,
  transparencyEffects: true,
  animations: true,
  blurStrength: 10,
  scale: 100
})

const updateDisplaySettings = async (settings) => {
  displaySettings.value = settings
  
  // 保存到服务器
  try {
    await valueUser('display_settings', JSON.stringify(settings))
    ElMessage.success('显示设置已保存')
    
    // 通知其他组件显示设置已更新
    window.dispatchEvent(new CustomEvent('display-settings-updated', {
      detail: settings
    }))
  } catch (error) {
    console.error('保存显示设置失败:', error)
    ElMessage.warning('保存显示设置失败')
  }
}

const loadDisplaySettings = async () => {
  try {
    const response = await keyUser('display_settings')
    if (response && response.code === 200 && response.data) {
      // 如果 data 是字符串，解析它；如果已经是对象，检查是否有 value 字段
      let settingsData = response.data
      if (typeof settingsData === 'string') {
        settingsData = JSON.parse(settingsData)
      } else if (settingsData.value) {
        settingsData = JSON.parse(settingsData.value)
      }
      displaySettings.value = { ...displaySettings.value, ...settingsData }
    }
  } catch (error) {
    console.error('加载显示设置失败:', error)
    // 加载失败时保留默认值
  }
}

// 当前壁纸
const currentWallpaper = ref({
  type: 'image',
  url: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=1920'
})

// 静态壁纸列表
const staticWallpapers = ref([
  {
    type: 'image',
    name: '渐变紫',
    url: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=1920',
    thumb: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=200'
  },
  {
    type: 'image',
    name: '蓝色科技',
    url: 'https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1920',
    thumb: 'https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=200'
  },
  {
    type: 'image',
    name: '抽象艺术',
    url: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=1920',
    thumb: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=200'
  },
  {
    type: 'image',
    name: '自然风光',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920',
    thumb: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=200'
  },
  {
    type: 'image',
    name: '城市夜景',
    url: 'https://images.unsplash.com/photo-1514565131-fce0801e5785?w=1920',
    thumb: 'https://images.unsplash.com/photo-1514565131-fce0801e5785?w=200'
  },
  {
    type: 'image',
    name: '星空',
    url: 'https://images.unsplash.com/photo-1419242902214-272b3f66ee7a?w=1920',
    thumb: 'https://images.unsplash.com/photo-1419242902214-272b3f66ee7a?w=200'
  },
  {
    type: 'image',
    name: '山峦日落',
    url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920',
    thumb: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=200'
  },
  {
    type: 'image',
    name: '海洋波浪',
    url: 'https://images.unsplash.com/photo-1505142468610-359e7d316be0?w=1920',
    thumb: 'https://images.unsplash.com/photo-1505142468610-359e7d316be0?w=200'
  }
])

// 动态壁纸列表
const dynamicWallpapers = ref([
  {
    id: 'particle',
    type: 'dynamic',
    name: '粒子星空',
    desc: '浪漫的粒子效果',
    icon: markRaw(Star),
    preview: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    component: markRaw(ParticleBackground),
    config: {
      count: 80,
      speed: 'medium',
      color: '#fff',
      size: 'medium',
      twinkle: true,
      shape: 'circle'
    }
  },
  {
    id: 'bubble',
    type: 'dynamic',
    name: '彩色气泡',
    desc: '清新的气泡飘动',
    icon: markRaw(Basketball),
    preview: 'linear-gradient(180deg, #e0f7fa 0%, #b2ebf2 50%, #80deea 100%)',
    component: markRaw(BubbleBackground),
    config: {
      count: 25,
      speed: 'slow',
      color: 'rainbow',
      size: 'large'
    }
  },
  {
    id: 'matrix',
    type: 'dynamic',
    name: '黑客帝国',
    desc: '数字矩阵雨',
    icon: markRaw(Grid),
    preview: 'linear-gradient(135deg, #000000 0%, #0a1f0a 100%)',
    component: markRaw(MatrixBackground),
    config: {
      color: '#00ff00',
      speed: 'medium',
      density: 'high'
    }
  },
  {
    id: 'geometry',
    type: 'dynamic',
    name: '几何图形',
    desc: '抽象几何动画',
    icon: markRaw(PieChart),
    preview: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
    component: markRaw(GeometryBackground),
    config: {
      shape: 'circles',
      color: '#667eea',
      animation: 'rotate'
    }
  },
  {
    id: 'star',
    type: 'dynamic',
    name: '星空闪烁',
    desc: '璀璨的星空',
    icon: markRaw(Sunny),
    preview: 'linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%)',
    component: markRaw(StarBackground),
    config: {
      count: 100,
      twinkle: true
    }
  },
  {
    id: 'wave',
    type: 'dynamic',
    name: '波浪涌动',
    desc: '流动的波浪',
    icon: markRaw(TrendCharts),
    preview: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    component: markRaw(WaveBackground),
    config: {
      color: 'gradient',
      speed: 'medium'
    }
  },
  {
    id: 'neon',
    type: 'dynamic',
    name: '霓虹线条',
    desc: '炫酷霓虹效果',
    icon: markRaw(Lightning),
    preview: 'linear-gradient(135deg, #000000 0%, #1a1a2e 100%)',
    component: markRaw(NeonBackground),
    config: {
      style: 'lines',
      color: 'rainbow'
    }
  },
  {
    id: 'gradient',
    type: 'dynamic',
    name: '渐变幻彩',
    desc: '流动的渐变色',
    icon: markRaw(MagicStick),
    preview: 'linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%)',
    component: markRaw(GradientBackground),
    config: {
      colors: ['#667eea', '#764ba2', '#f093fb', '#f5576c'],
      speed: 'medium'
    }
  },
  {
    id: 'snow',
    type: 'dynamic',
    name: '飘雪',
    desc: '唯美的雪花飘落',
    icon: markRaw(Cloudy),
    preview: 'linear-gradient(180deg, #e6f2ff 0%, #c3dafe 100%)',
    component: markRaw(SnowBackground),
    config: {
      count: 100,
      speed: 'slow'
    }
  },
  {
    id: 'fireworks',
    type: 'dynamic',
    name: '烟花绽放',
    desc: '绚丽的烟花',
    icon: markRaw(Service),
    preview: 'linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%)',
    component: markRaw(FireworksBackground),
    config: {
      frequency: 'medium'
    }
  },
  {
    id: 'abstract',
    type: 'dynamic',
    name: '抽象流体',
    desc: '艺术流体动画',
    icon: markRaw(Operation),
    preview: 'linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%)',
    component: markRaw(AbstractBackground),
    config: {
      style: 'fluid',
      colors: ['#667eea', '#764ba2', '#f093fb']
    }
  },
  {
    id: 'scan',
    type: 'dynamic',
    name: '扫描线',
    desc: '科技扫描效果',
    icon: markRaw(Histogram),
    preview: 'linear-gradient(135deg, #0a192f 0%, #112240 100%)',
    component: markRaw(ScanBackground),
    config: {
      color: '#00ff88',
      speed: 'medium'
    }
  },
  {
    id: 'rainbow-flow',
    type: 'dynamic',
    name: '彩虹流光',
    desc: '梦幻的彩虹流动',
    icon: markRaw(MagicStick),
    preview: 'linear-gradient(135deg, #ff0080 0%, #8000ff 25%, #0080ff 50%, #00ff80 75%, #ffff00 100%)',
    component: markRaw(RainbowFlowBackground),
    config: {}
  },
  {
    id: 'aurora',
    type: 'dynamic',
    name: '极光之夜',
    desc: '北极光的美丽',
    icon: markRaw(Cloudy),
    preview: 'linear-gradient(to bottom, #050a1e 0%, #0a1e3e 50%, #1a2e4e 100%)',
    component: markRaw(AuroraBackground),
    config: {}
  },
  {
    id: 'light-ripple',
    type: 'dynamic',
    name: '光波涟漪',
    desc: '点击产生涟漪',
    icon: markRaw(TrendCharts),
    preview: 'linear-gradient(135deg, #0a0a1e 0%, #1a1a3e 100%)',
    component: markRaw(LightRippleBackground),
    config: {}
  },
  {
    id: 'time-tunnel',
    type: 'dynamic',
    name: '时空隧道',
    desc: '穿越时空的通道',
    icon: markRaw(Service),
    preview: 'radial-gradient(circle, #000a1e 0%, #000000 100%)',
    component: markRaw(TimeTunnelBackground),
    config: {}
  },
  {
    id: 'digital-rain',
    type: 'dynamic',
    name: '彩色数字雨',
    desc: '增强版矩阵代码',
    icon: markRaw(Grid),
    preview: 'linear-gradient(135deg, #000000 0%, #001a00 100%)',
    component: markRaw(DigitalRainBackground),
    config: {}
  },
  {
    id: 'cosmic',
    type: 'dynamic',
    name: '宇宙穿梭',
    desc: '高速穿越星空',
    icon: markRaw(Star),
    preview: 'radial-gradient(circle at center, #000a1e 0%, #000000 100%)',
    component: markRaw(CosmicBackground),
    config: {}
  },
  {
    id: 'plasma',
    type: 'dynamic',
    name: '等离子体',
    desc: '复古等离子效果',
    icon: markRaw(Operation),
    preview: 'linear-gradient(135deg, #ff00ff 0%, #00ffff 50%, #ffff00 100%)',
    component: markRaw(PlasmaBackground),
    config: {}
  },
  {
    id: 'sakura',
    type: 'dynamic',
    name: '樱花飘落',
    desc: '浪漫的樱花雨',
    icon: markRaw(Cloudy),
    preview: 'linear-gradient(180deg, #ffeef8 0%, #ffe5f0 50%, #ffd4e5 100%)',
    component: markRaw(SakuraBackground),
    config: {}
  },
  {
    id: 'meteor-shower',
    type: 'dynamic',
    name: '流星雨',
    desc: '璀璨的流星划过',
    icon: markRaw(Star),
    preview: 'radial-gradient(circle, #0a0a20 0%, #050515 50%, #000000 100%)',
    component: markRaw(MeteorShowerBackground),
    config: {}
  },
  {
    id: 'butterfly',
    type: 'dynamic',
    name: '蝴蝶飞舞',
    desc: '花丛中的蝴蝶',
    icon: markRaw(Sunny),
    preview: 'linear-gradient(180deg, #87CEEB 0%, #B0E0E6 50%, #E0F6FF 100%)',
    component: markRaw(ButterflyBackground),
    config: {}
  },
  {
    id: 'dna-helix',
    type: 'dynamic',
    name: 'DNA螺旋',
    desc: '生命的密码',
    icon: markRaw(TrendCharts),
    preview: 'radial-gradient(circle, #0a1520 0%, #051015 50%, #000508 100%)',
    component: markRaw(DNAHelixBackground),
    config: {}
  },
  {
    id: 'circuit-board',
    type: 'dynamic',
    name: '电路板',
    desc: '科技电路脉冲',
    icon: markRaw(Grid),
    preview: 'linear-gradient(135deg, #0a1520 0%, #0d1a25 50%, #0a1520 100%)',
    component: markRaw(CircuitBoardBackground),
    config: {}
  },
  {
    id: 'heartbeat',
    type: 'dynamic',
    name: '心跳律动',
    desc: '生命的节奏',
    icon: markRaw(Service),
    preview: 'radial-gradient(circle, #1a0a0f 0%, #0f0508 50%, #000000 100%)',
    component: markRaw(HeartBeatBackground),
    config: {}
  }
])

// 加载壁纸
const loadWallpaper = async () => {
  try {
    const response = await keyUser('desktop_wallpaper')
    console.log('壁纸API响应:', response)
    
    // 检查响应格式：{ code: 200, data: { value: "..." }, message: "..." }
    if (response && response.code === 200 && response.data) {
      // 如果 data 是字符串，解析它；如果已经是对象，检查是否有 value 字段
      let wallpaperData = response.data
      if (typeof wallpaperData === 'string') {
        wallpaperData = JSON.parse(wallpaperData)
      } else if (wallpaperData.value) {
        wallpaperData = JSON.parse(wallpaperData.value)
      }
      
      console.log('解析后的壁纸数据:', wallpaperData)
      
      // 设置动态壁纸的component
      if (wallpaperData.type === 'dynamic' && wallpaperData.id) {
        const dynamic = dynamicWallpapers.value.find(w => w.id === wallpaperData.id)
        console.log('找到动态壁纸配置:', dynamic)
        if (dynamic && dynamic.component) {
          wallpaperData.component = dynamic.component
        }
      }
      currentWallpaper.value = wallpaperData
      console.log('最终壁纸配置:', currentWallpaper.value)
    }
  } catch (error) {
    console.error('加载壁纸失败:', error)
    // 使用默认壁纸
    currentWallpaper.value = {
      type: 'image',
      url: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=1920'
    }
  }
}

// 切换壁纸
const changeWallpaper = async (wallpaper) => {
  currentWallpaper.value = wallpaper
  wallpaperDialog.value = false
  
  // 保存壁纸到服务器
  try {
    // 创建一个可序列化的壁纸对象（排除component和icon）
    const serializableWallpaper = {
      id: wallpaper.id,
      type: wallpaper.type,
      url: wallpaper.url,
      thumb: wallpaper.thumb,
      name: wallpaper.name,
      desc: wallpaper.desc,
      config: wallpaper.config
    }
    await valueUser('desktop_wallpaper', JSON.stringify(serializableWallpaper))
  } catch (error) {
    console.error('保存壁纸失败:', error)
    ElMessage.warning('保存壁纸失败')
  }
}

// ==================== 应用管理 ====================
const appManageDialog = ref(false)

// 所有可用应用列表
const availableApps = ref([
  // 核心业务
  {
    id: 'dashboard',
    name: '数据概览',
    description: '企业运营数据总览',
    icon: markRaw(HomeFilled),
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    path: '/dashboard',
    category: 'core'
  },
  {
    id: 'cockpit',
    name: '驾驶舱',
    description: '数据驾驶舱',
    icon: markRaw(Platform),
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    path: '/cockpit/overview',
    category: 'core'
  },
  
  // 销售管理
  {
    id: 'sales',
    name: '销售管理',
    description: '销售订单与客户管理',
    icon: markRaw(ShoppingCart),
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    path: '/sales/cashier',
    category: 'sales'
  },
  
  // 采购管理
  {
    id: 'purchase',
    name: '采购管理',
    description: '采购订单与供应商管理',
    icon: markRaw(TakeawayBox),
    color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    path: '/purchase/orders',
    category: 'purchase'
  },
  
  // 库存管理
  {
    id: 'inventory',
    name: '库存管理',
    description: '商品库存管理',
    icon: markRaw(Box),
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    path: '/inventory/products',
    category: 'inventory'
  },
  {
    id: 'warehouse',
    name: '仓库管理',
    description: '仓库出入库管理',
    icon: markRaw(House),
    color: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)',
    path: '/inventory/warehouses',
    category: 'inventory'
  },
  
  // 财务管理
  {
    id: 'finance',
    name: '财务管理',
    description: '财务核算与报表',
    icon: markRaw(Money),
    color: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    path: '/finance/overview',
    category: 'finance'
  },
  
  // 生产管理
  {
    id: 'manufacturing',
    name: '生产管理',
    description: '生产计划与工单',
    icon: markRaw(Tools),
    color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
    path: '/manufacturing/production',
    category: 'manufacturing'
  },
  
  // 报表中心
  {
    id: 'reports',
    name: '报表中心',
    description: '统计报表与分析',
    icon: markRaw(DataBoard),
    color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    path: '/reports/center',
    category: 'report'
  },
  
  // 会员管理
  {
    id: 'member',
    name: '会员管理',
    description: '会员与积分管理',
    icon: markRaw(UserFilled),
    color: 'linear-gradient(135deg, #ff6b6b 0%, #ffd93d 100%)',
    path: '/member/list',
    category: 'member'
  },
  
  // 项目管理
  {
    id: 'project',
    name: '项目管理',
    description: '项目任务管理',
    icon: markRaw(Management),
    color: 'linear-gradient(135deg, #6a11cb 0%, #2575fc 100%)',
    path: '/project/list',
    category: 'project'
  },
  
  // 人力资源
  {
    id: 'hr',
    name: '人力资源',
    description: '员工与考勤管理',
    icon: markRaw(Suitcase),
    color: 'linear-gradient(135deg, #ee0979 0%, #ff6a00 100%)',
    path: '/hr/employees',
    category: 'hr'
  },
  
  // 办公管理
  {
    id: 'office',
    name: '办公管理',
    description: 'OA办公系统',
    icon: markRaw(OfficeBuilding),
    color: 'linear-gradient(135deg, #12c2e9 0%, #c471ed 100%)',
    path: '/office/workflow',
    category: 'office'
  },
  
  // 合同管理
  {
    id: 'contract',
    name: '合同管理',
    description: '合同签订与管理',
    icon: markRaw(Stamp),
    color: 'linear-gradient(135deg, #f857a6 0%, #ff5858 100%)',
    path: '/contract/list',
    category: 'contract'
  },
  
  // 资产管理
  {
    id: 'asset',
    name: '资产管理',
    description: '固定资产管理',
    icon: markRaw(Wallet),
    color: 'linear-gradient(135deg, #3f2b96 0%, #a8c0ff 100%)',
    path: '/asset/list',
    category: 'asset'
  },
  
  // 设备管理
  {
    id: 'equipment',
    name: '设备管理',
    description: '设备维护保养',
    icon: markRaw(Tools),
    color: 'linear-gradient(135deg, #ff512f 0%, #dd2476 100%)',
    path: '/equipment/list',
    category: 'equipment'
  },
  
  // 基础数据
  {
    id: 'basedata',
    name: '基础数据',
    description: '系统基础数据',
    icon: markRaw(Goods),
    color: 'linear-gradient(135deg, #2193b0 0%, #6dd5ed 100%)',
    path: '/basedata/products',
    category: 'system'
  },
  
  // 低代码平台
  {
    id: 'lowcode',
    name: '低代码平台',
    description: '可视化开发平台',
    icon: markRaw(Menu),
    color: 'linear-gradient(135deg, #fc466b 0%, #3f5efb 100%)',
    path: '/lowcode/designer',
    category: 'development'
  },
  
  // CMS内容管理
  {
    id: 'cms',
    name: '内容管理',
    description: 'CMS内容管理',
    icon: markRaw(DocumentCopy),
    color: 'linear-gradient(135deg, #00c6ff 0%, #0072ff 100%)',
    path: '/cms/articles',
    category: 'content'
  },
  
  // 学习中心
  {
    id: 'learning',
    name: '学习中心',
    description: '在线学习平台',
    icon: markRaw(Reading),
    color: 'linear-gradient(135deg, #f77062 0%, #fe5196 100%)',
    path: '/learning/games',
    category: 'training'
  },
  
  // 商城管理
  {
    id: 'mall',
    name: '商城管理',
    description: '电商平台管理',
    icon: markRaw(PriceTag),
    color: 'linear-gradient(135deg, #ffd89b 0%, #19547b 100%)',
    path: '/mall/products',
    category: 'mall'
  },
  
  // 实施管理
  {
    id: 'implementation',
    name: '实施管理',
    description: '项目实施管理',
    icon: markRaw(Tickets),
    color: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
    path: '/implementation/projects',
    category: 'implementation'
  },
  
  // 待办事项
  {
    id: 'todos',
    name: '待办事项',
    description: '待办事项管理与看板',
    icon: markRaw(DocumentChecked),
    color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    path: '/office/todos',
    category: 'office'
  },
  
  // 系统设置
  {
    id: 'system',
    name: '系统设置',
    description: '系统配置与管理',
    icon: markRaw(Setting),
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    path: '/system/users',
    category: 'system'
  }
])

// 桌面图标（从localStorage加载，或使用默认值）
const desktopIcons = ref([])

// 初始化桌面图标
const initDesktopIcons = async () => {
  try {
    const response = await keyUser('desktop_icons')
    if (response && response.code === 200 && response.data) {
      // 如果 data 是字符串，解析它；如果已经是对象，检查是否有 value 字段
      let iconsData = response.data
      if (typeof iconsData === 'string') {
        iconsData = JSON.parse(iconsData)
      } else if (iconsData.value) {
        iconsData = JSON.parse(iconsData.value)
      }
      
      // 恢复图标组件引用
      const icons = Array.isArray(iconsData) ? iconsData : []
      desktopIcons.value = icons.map(icon => {
        const app = availableApps.value.find(a => a.id === icon.id)
        return {
          ...icon,
          icon: app ? app.icon : markRaw(Monitor),
          color: app ? app.color : '#409eff'
        }
      })
    } else {
      setDefaultDesktopIcons()
    }
  } catch (e) {
    console.error('加载桌面图标失败:', e)
    setDefaultDesktopIcons()
  }
}

// 设置默认桌面图标
const setDefaultDesktopIcons = () => {
  desktopIcons.value = [
    {
      id: 'dashboard',
      label: '数据概览',
      icon: markRaw(HomeFilled),
      color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      path: '/dashboard',
      x: 30,
      y: 30
    },
    {
      id: 'sales',
      label: '销售管理',
      icon: markRaw(ShoppingCart),
      color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
      path: '/sales/cashier',
      x: 30,
      y: 140
    },
    {
      id: 'inventory',
      label: '库存管理',
      icon: markRaw(Box),
      color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
      path: '/inventory/products',
      x: 30,
      y: 250
    },
    {
      id: 'finance',
      label: '财务管理',
      icon: markRaw(Money),
      color: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
      path: '/finance/overview',
      x: 30,
      y: 360
    },
    {
      id: 'member',
      label: '会员管理',
      icon: markRaw(UserFilled),
      color: 'linear-gradient(135deg, #ff6b6b 0%, #ffd93d 100%)',
      path: '/member/list',
      x: 150,
      y: 30
    },
    {
      id: 'reports',
      label: '报表中心',
      icon: markRaw(DataBoard),
      color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
      path: '/reports/center',
      x: 150,
      y: 140
    }
  ]
  saveDesktopIcons()
}

// 保存桌面图标
const saveDesktopIcons = async () => {
  const iconsToSave = desktopIcons.value.map(icon => ({
    id: icon.id,
    label: icon.label,
    path: icon.path,
    x: icon.x,
    y: icon.y
  }))
  
  try {
    await valueUser('desktop_icons', JSON.stringify(iconsToSave))
  } catch (error) {
    console.error('保存桌面图标失败:', error)
  }
}

// 添加应用到桌面
const addAppToDesktop = (app) => {
  // 计算新图标位置（按列排列）
  const column = Math.floor(desktopIcons.value.length / 6)
  const row = desktopIcons.value.length % 6
  const x = 30 + column * 120
  const y = 30 + row * 110
  
  desktopIcons.value.push({
    id: app.id,
    label: app.name,
    icon: app.icon,
    color: app.color,
    path: app.path,
    x,
    y
  })
  
  saveDesktopIcons()
  ElMessage.success(`已添加"${app.name}"到桌面`)
}

// 从桌面移除应用
const removeAppFromDesktop = (index) => {
  const icon = desktopIcons.value[index]
  desktopIcons.value.splice(index, 1)
  saveDesktopIcons()
  ElMessage.success(`已移除"${icon.label}"`)
}

// 清空桌面
const clearDesktop = () => {
  ElMessageBox.confirm(
    '确定要清空桌面吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    desktopIcons.value = []
    saveDesktopIcons()
    ElMessage.success('桌面已清空')
  }).catch(() => {})
}

// 排序桌面图标（按名称排序）
const sortDesktopIcons = () => {
  if (desktopIcons.value.length === 0) return
  
  // 按名称排序
  const sorted = [...desktopIcons.value].sort((a, b) => {
    const labelA = (a.label || '').toLowerCase()
    const labelB = (b.label || '').toLowerCase()
    return labelA.localeCompare(labelB, 'zh-CN')
  })
  
  // 重新计算位置（从左到右、从上到下排列）
  const iconSpacing = displaySettings.value.iconSpacing || 110
  const iconSize = displaySettings.value.iconSize || 56
  const startX = 30
  const startY = 30
  const iconsPerRow = Math.floor((window.innerWidth - startX * 2) / iconSpacing)
  
  sorted.forEach((icon, index) => {
    const row = Math.floor(index / iconsPerRow)
    const col = index % iconsPerRow
    icon.x = startX + col * iconSpacing
    icon.y = startY + row * iconSpacing
  })
  
  desktopIcons.value = sorted
  saveDesktopIcons()
  ElMessage.success('桌面图标已按名称排序')
}

// 打开应用管理
const openAppManage = () => {
  appManageDialog.value = true
}

const selectedIcons = ref([])

const selectIcon = (id, event) => {
  if (!event.ctrlKey) {
    selectedIcons.value = [id]
  } else {
    const index = selectedIcons.value.indexOf(id)
    if (index > -1) {
      selectedIcons.value.splice(index, 1)
    } else {
      selectedIcons.value.push(id)
    }
  }
}

const openIcon = (icon) => {
  // 直接跳转到应用页面
  if (icon.path) {
    router.push(icon.path)
  }
}

// ==================== 图标拖拽 ====================
let draggedIcon = null
let dragOffsetX = 0
let dragOffsetY = 0

const startDrag = (icon, event) => {
  if (event.button !== 0) return // 只响应左键
  
  draggedIcon = icon
  dragOffsetX = event.clientX - icon.x
  dragOffsetY = event.clientY - icon.y

  document.addEventListener('mousemove', onIconDrag)
  document.addEventListener('mouseup', onIconDragEnd)
}

const onIconDrag = (event) => {
  if (!draggedIcon) return
  
  draggedIcon.x = Math.max(0, Math.min(event.clientX - dragOffsetX, window.innerWidth - 100))
  draggedIcon.y = Math.max(0, Math.min(event.clientY - dragOffsetY, window.innerHeight - 150))
}

const onIconDragEnd = () => {
  draggedIcon = null
  document.removeEventListener('mousemove', onIconDrag)
  document.removeEventListener('mouseup', onIconDragEnd)
  // 保存图标位置
  saveDesktopIcons()
}

// ==================== 窗口管理 ====================
const openWindows = ref([])
const activeWindow = ref(null)

const closeWindow = (id) => {
  const index = openWindows.value.findIndex(w => w.id === id)
  if (index > -1) {
    openWindows.value.splice(index, 1)
    if (activeWindow.value === id) {
      activeWindow.value = openWindows.value.length > 0 ? openWindows.value[openWindows.value.length - 1].id : null
    }
  }
}

const minimizeWindow = (id) => {
  const window = openWindows.value.find(w => w.id === id)
  if (window) {
    window.minimized = true
    if (activeWindow.value === id) {
      const visibleWindows = openWindows.value.filter(w => !w.minimized)
      activeWindow.value = visibleWindows.length > 0 ? visibleWindows[visibleWindows.length - 1].id : null
    }
  }
}

const toggleMaximize = (id) => {
  const window = openWindows.value.find(w => w.id === id)
  if (window) {
    window.maximized = !window.maximized
  }
}

const activateWindow = (id) => {
  const window = openWindows.value.find(w => w.id === id)
  if (window) {
    window.minimized = false
    activeWindow.value = id
    
    // 将窗口移到最前面
    const index = openWindows.value.findIndex(w => w.id === id)
    if (index > -1) {
      const [win] = openWindows.value.splice(index, 1)
      openWindows.value.push(win)
    }
  }
}

// ==================== 窗口拖拽 ====================
let draggedWindow = null
let windowDragOffsetX = 0
let windowDragOffsetY = 0

const startWindowDrag = (window, event) => {
  if (window.maximized) return
  if (event.button !== 0) return
  
  draggedWindow = window
  windowDragOffsetX = event.clientX - window.x
  windowDragOffsetY = event.clientY - window.y

  document.addEventListener('mousemove', onWindowDrag)
  document.addEventListener('mouseup', onWindowDragEnd)
}

const onWindowDrag = (event) => {
  if (!draggedWindow) return
  
  draggedWindow.x = Math.max(0, Math.min(event.clientX - windowDragOffsetX, window.innerWidth - 100))
  draggedWindow.y = Math.max(0, Math.min(event.clientY - windowDragOffsetY, window.innerHeight - 100))
}

const onWindowDragEnd = () => {
  draggedWindow = null
  document.removeEventListener('mousemove', onWindowDrag)
  document.removeEventListener('mouseup', onWindowDragEnd)
}

// ==================== 窗口调整大小 ====================
let resizedWindow = null
let resizeStartX = 0
let resizeStartY = 0
let resizeStartWidth = 0
let resizeStartHeight = 0

const startResize = (window, event) => {
  if (event.button !== 0) return
  
  resizedWindow = window
  resizeStartX = event.clientX
  resizeStartY = event.clientY
  resizeStartWidth = window.width
  resizeStartHeight = window.height

  document.addEventListener('mousemove', onWindowResize)
  document.addEventListener('mouseup', onWindowResizeEnd)
}

const onWindowResize = (event) => {
  if (!resizedWindow) return
  
  const deltaX = event.clientX - resizeStartX
  const deltaY = event.clientY - resizeStartY
  
  resizedWindow.width = Math.max(400, resizeStartWidth + deltaX)
  resizedWindow.height = Math.max(300, resizeStartHeight + deltaY)
}

const onWindowResizeEnd = () => {
  resizedWindow = null
  document.removeEventListener('mousemove', onWindowResize)
  document.removeEventListener('mouseup', onWindowResizeEnd)
}

// ==================== 右键菜单 ====================
const contextMenu = ref({
  show: false,
  x: 0,
  y: 0,
  items: []
})

const showDesktopContextMenu = (event) => {
  contextMenu.value = {
    show: true,
    x: event.clientX,
    y: event.clientY,
    items: [
      {
        label: '应用管理',
        icon: markRaw(Platform),
        action: () => {
          openAppManage()
          hideContextMenu()
        }
      },
      { divider: true },
      {
        label: '查看',
        icon: markRaw(ElementPlusIconsVue.View),
        action: () => {}
      },
      {
        label: '排序方式',
        icon: markRaw(ElementPlusIconsVue.Sort),
        action: () => {
          sortDesktopIcons()
          hideContextMenu()
        }
      },
      { divider: true },
      {
        label: '刷新',
        icon: markRaw(Refresh),
        shortcut: 'F5',
        action: () => location.reload()
      },
      { divider: true },
      {
        label: '个性化',
        icon: markRaw(Picture),
        action: () => {
          wallpaperDialog.value = true
          hideContextMenu()
        }
      },
      {
        label: '显示设置',
        icon: markRaw(Setting),
        action: () => {
          displaySettingsDialog.value = true
          hideContextMenu()
        }
      }
    ]
  }
}

const showIconContextMenu = (icon, event) => {
  contextMenu.value = {
    show: true,
    x: event.clientX,
    y: event.clientY,
    items: [
      {
        label: '打开',
        icon: markRaw(FolderOpened),
        action: () => {
          openIcon(icon)
          hideContextMenu()
        }
      },
      { divider: true },
      {
        label: '删除',
        icon: markRaw(ElementPlusIconsVue.Delete),
        action: () => {
          const index = desktopIcons.value.findIndex(i => i.id === icon.id)
          if (index > -1) {
            desktopIcons.value.splice(index, 1)
          }
          hideContextMenu()
        }
      },
      {
        label: '重命名',
        icon: markRaw(ElementPlusIconsVue.Edit),
        action: () => hideContextMenu()
      },
      { divider: true },
      {
        label: '属性',
        icon: markRaw(Files),
        action: () => hideContextMenu()
      }
    ]
  }
}

const hideContextMenu = () => {
  contextMenu.value.show = false
}

// ==================== 开始菜单 ====================
const toggleStartMenu = () => {
  // 这里可以触发 Win10Layout 中的开始菜单
  console.log('打开开始菜单')
}

// ==================== 系统托盘功能 ====================
const showNotifications = () => {
  console.log('显示通知中心')
}

const showCalendar = () => {
  console.log('显示日历')
}

// ==================== 生命周期 ====================
let timeInterval = null

onMounted(() => {
  updateDateTime()
  timeInterval = setInterval(updateDateTime, 1000)
  
  // 初始化桌面图标
  initDesktopIcons()
  
  // 加载显示设置
  loadDisplaySettings()
  
  // 加载壁纸
  loadWallpaper()
  
  // 点击其他地方隐藏右键菜单
  document.addEventListener('click', hideContextMenu)
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
  document.removeEventListener('click', hideContextMenu)
  document.removeEventListener('mousemove', onIconDrag)
  document.removeEventListener('mouseup', onIconDragEnd)
  document.removeEventListener('mousemove', onWindowDrag)
  document.removeEventListener('mouseup', onWindowDragEnd)
  document.removeEventListener('mousemove', onWindowResize)
  document.removeEventListener('mouseup', onWindowResizeEnd)
})
</script>

<style scoped>
.win10-desktop {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  background: #000;
  user-select: none;
}
</style>
